package com.example.statistics.controller;


import com.example.commonutils.ResultData;
import com.example.servicebase.exceptionhandler.CustomException;
import com.example.statistics.service.DailyService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-06-07
 */
@RestController
@RequestMapping("/statistics/daily")
public class DailyController {
    @Autowired
    private DailyService dailyService;

    //统计某一天的注册人数
    @PostMapping(value = "registerCount/{date}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData registerCount(@PathVariable String date) {
        dailyService.registerCount(date);
        return ResultData.ok();
    }

    @GetMapping(value = "showData/{type}/{start}/{end}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData showData(@PathVariable String type,
                               @PathVariable String start,
                               @PathVariable String end) {
        if (StringUtil.isNullOrEmpty(type) ||
                StringUtil.isNullOrEmpty(start) ||
                StringUtil.isNullOrEmpty(end)) {
            throw new CustomException(20001,"请将条件选择完整！");
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        Date To = null;
        try {
            To = dateFormat.parse(end);
        } catch (ParseException e) {
            throw new CustomException(20001, "统计时出错，请稍后再试...");
        }
        if (To.after(now)) {
            throw new CustomException(20001, "统计日期不得超过今天！");
        }
        Map<String, Object> map = dailyService.getShowData(type, start, end);
        return ResultData.ok().data(map);
    }
}

